<template>
    <el-card class="box-card">
        <template #header>
            <div class="card-header">
                <el-form :inline="true" :model="findForm" class="demo-form-inline">
                    <el-form-item label="团队名称：">
                        <el-input v-model="findForm.name" placeholder="请输入团队名称" style="width: 200px" clearable />
                    </el-form-item>
                    <el-form-item label="项目名称：">
                        <el-input v-model="findForm.itemName" placeholder="请输入项目名称" style="width: 200px" clearable />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="userItemFindAll(findForm)">查询</el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="success" @click="addUserItem()">创建团队</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </template>
        <el-table :data="userItemData" style="width: 100%" max-height="800">
            <el-table-column type="index" width="50" />
            <el-table-column property="name" label="团队名称" width="300" />
            <el-table-column property="itemName" label="项目名称" width="300" />
            <el-table-column property="userName" label="负责人姓名" width="120" />
            <el-table-column property="userNameOne" label="成员1姓名" width="120" />
            <el-table-column property="userNameTwo" label="成员2姓名" width="120" />
            <el-table-column property="userNameThree" label="成员3姓名" width="120" />
            <el-table-column property="createdAt" label="创建日期" width="120" />
            <el-table-column property="updateAt" label="修改日期" width="120" />
            <el-table-column label="操作" width="200">
                <template #default="scope">
                    <el-button type="primary" @click="updateUserItem(scope.row)">修改</el-button>
                    <el-button type="danger" @click="deleteUserItem(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
    </el-card>
    <!-- 添加和修改 -->
    <el-dialog v-model="dialogForm" :title="dialogTitle" width="800">
        <el-form ref="ruleFormRef" style="max-width: 600px" :model="userItemForm" :rules="rules" label-width="auto"
            class="demo-ruleForm" status-icon>
            <el-form-item label="团队名称" prop="name">
                <el-input v-model="userItemForm.name" />
            </el-form-item>
            <el-form-item label="项目名称" >
                <el-input v-model="userItemForm.itemName"  >
                    <template #suffix>
                        <el-icon class="el-input__icon"  @click="chooseDate({type: 'item',number: 9})">
                            <Folder />
                        </el-icon>
                    </template>
                </el-input>
            </el-form-item>
            <el-form-item label="项目负责人" prop="userName">
                <el-input v-model="userItemForm.userName" />
            </el-form-item>
            <el-form-item label="成员1姓名" prop="userNameOne">
                <el-input v-model="userItemForm.userNameOne" >
                    <template #suffix>
                        <el-icon class="el-input__icon"  @click="chooseDate({type: 'user',number: 1})">
                            <User />
                        </el-icon>
                    </template>
                </el-input>
            </el-form-item>
            <el-form-item label="成员2姓名" prop="userNameTwo">
                <el-input v-model="userItemForm.userNameTwo" >
                    <template #suffix>
                        <el-icon class="el-input__icon"  @click="chooseDate({type: 'user',number: 2})">
                            <User />
                        </el-icon>
                    </template>
                </el-input>
            </el-form-item>
            <el-form-item label="成员3姓名" prop="userNameThree">
                <el-input v-model="userItemForm.userNameThree" >
                    <template #suffix>
                        <el-icon class="el-input__icon"  @click="chooseDate({type: 'user',number: 3})">
                            <User />
                        </el-icon>
                    </template>
                </el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="addOrUpdateUserItem({title: dialogTitle,data: userItemForm})">提交</el-button>
                <el-button type="primary" @click="dialogForm = false">
                    取消
                </el-button>
            </div>
        </template>
    </el-dialog>
    <!-- 选择成员和项目 -->
    <el-dialog v-model="dialogForm1" :title="dialogTitle1" width="500">
        <el-table :data="dateArr" style="width: 100%" max-height="800" :header-cell-style="{ 'text-align': 'center' }"
            :cell-style="{ 'text-align': 'center' }">
            <el-table-column type="index" width="50" />
            <el-table-column v-if="dateNumber != 9" property="avatarUrl" label="头像" width="110">
                <template #default="scope">
                    <div>
                        <el-image v-if="scope.row.avatarUrl" style="width: 100px; height: 100px"
                            :src="scope.row.avatarUrl" :preview-src-list="[scope.row.avatarUrl]" fit="fill" />
                    </div>
                </template>
            </el-table-column>
            <el-table-column v-if="dateNumber == 9" property="imagePath" label="项目图片" width="110">
                <template #default="scope">
                    <div>
                        <el-image v-if="scope.row.imagePath" style="width: 100px; height: 100px"
                            :src="scope.row.imagePath" :preview-src-list="[scope.row.imagePath]" fit="fill" />
                    </div>
                </template>
            </el-table-column>
            <el-table-column v-if="dateNumber != 9" property="userName" label="用户名" width="80" />
            <el-table-column v-if="dateNumber == 9" property="name" label="项目名称" width="80" />
            <el-table-column label="确认" width="200">
                <template #default="scope">
                    <el-button v-if="dateNumber != 9" type="primary" @click="passOnDate(scope.row.userName)">选择</el-button>
                    <el-button v-if="dateNumber == 9" type="primary" @click="passOnDate(scope.row.name)">选择</el-button>
                </template>
            </el-table-column>
        </el-table>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="dialogForm1 = false">
                    取消
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { FindAllUserItem, AddUserItem, UpdateUserItem, DeleteUserItem } from '../../api/userItem';
import { FindItemById } from '../../api/item';
import { findAllUser } from '../../api/user';
// element-plus导入组件
import { ElMessage, ElNotification } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { User,Folder } from '@element-plus/icons-vue';
import dayjs from "dayjs";

// 页面跳转
import { useRouter } from 'vue-router';
const router = useRouter();
const errorId = sessionStorage.getItem('userRoleId')+''
if(errorId == undefined || errorId == '' || (errorId != '1' && errorId != '2')){
    sessionStorage.setItem('error','not')
    router.push("/LimitsAuthority")
}

const findForm = reactive({
    name: '',
    itemName: '',
    isPrincipal: 1,
})
const userItemFindAll = (findForm: object) => {
    FindAllUserItem(findForm).then((res: any) => {
        console.log(res)
        if (res.code == 2000) {
            userItemData.value = res.data
            userItemData.value.forEach((item: any) => {
                item.createdAt = dataFormat(item.createdAt)
                item.updateAt = dataFormat(item.updateAt)
            })
            console.log(userItemData.value)
        } else {
            ElMessage.error(res.message)
        }
    })
}
userItemFindAll(findForm)
const userItemData = ref([])
// 抽屉参数
const dialogForm = ref(false)
const dialogTitle = ref('')
const dialogForm1 = ref(false)
const dialogTitle1 = ref('')
const openDialog = (dialogData: string) => {
    dialogForm.value = true
    dialogTitle.value = dialogData
}
const openDialog1 = (dialogData: string) => {
    dialogForm1.value = true
    dialogTitle1.value = dialogData
}
const dateArr = ref([] as any[])
const dateNumber = ref(0)
const passOnDate = (date: string) => {
    if (dateNumber.value == 1) {
        userItemForm.userNameOne = date
    } else if (dateNumber.value == 2) {
        userItemForm.userNameTwo = date
    } else if (dateNumber.value == 3) {
        userItemForm.userNameThree = date
    } else if (dateNumber.value == 9) {
        userItemForm.itemName = date
    }
    dialogForm1.value = false
}
// 选择信息
const chooseDate = (date: any) => {
    dateNumber.value = date.number
    if (date.type == 'item') {
        openDialog1('选择项目')
        FindItemById({}).then((res: any) => {
            if (res.code == 2000) {
                dateArr.value = res.data
            } else {
                ElMessage.error(res.message)
            }
        })
    } else if (date.type == 'user') {
        openDialog1('选择成员')
        findAllUser({roleId: 1}).then((res: any) => {
            if (res.code == 2000) {
                dateArr.value = res.data
            } else {
                ElMessage.error(res.message)
            }
        })
    }

}
// 添加和修改
const addUserItem = () => {
    openDialog('添加团队信息')
    userItemForm.id = 0
    userItemForm.name = ''
    userItemForm.itemName = ''
    userItemForm.userName = sessionStorage.getItem('userName')+''
    userItemForm.userNameOne = ''
    userItemForm.userNameTwo = ''
    userItemForm.userNameThree = ''
}
const updateUserItem = (row: any) => {
    openDialog('修改团队信息')
    userItemForm.id = row.id
    userItemForm.name = row.name
    userItemForm.itemName = row.itemName
    userItemForm.userName = row.userName
    userItemForm.userNameOne = row.userNameOne
    userItemForm.userNameTwo = row.userNameTwo
    userItemForm.userNameThree = row.userNameThree
    userItemForm.isDel = row.isDel
}
const addOrUpdateUserItem = (data: any) => {
    if (!ruleFormRef.value) return;
    ruleFormRef.value.validate((valid: boolean) => {
        if (valid) {
            console.log('表单提交成功');
            // 处理添加或更新逻辑
            if (data.title === '添加团队信息') {
                AddUserItem(userItemForm).then((res: any) => {
                    if (res.code == 2000) {
                        ElNotification({
                            title: '成功',
                            message: '添加成功',
                            type: 'success',
                        });
                        dialogForm.value = false;
                        userItemFindAll(findForm);
                    } else {
                        ElMessage.error(res.message);
                    }
                });
            } else if (data.title === '修改团队信息') {
                UpdateUserItem(userItemForm).then((res: any) => {
                    if (res.code == 2000) {
                        ElNotification({
                            title: '成功',
                            message: '修改成功',
                            type: 'success',
                        });
                        dialogForm.value = false;
                        userItemFindAll(findForm);
                    } else {
                        ElMessage.error(res.message);
                    }
                });
            }
        } else {
            ElMessage.error('表单校验失败');
        }
    });
}
// 删除操作
const deleteUserItem = (data: any) => {
    DeleteUserItem(data).then((res: any) => {
        if (res.code == 2000) {
            ElNotification({
                title: '成功',
                message: '删除成功',
                type: 'success',
            });
            userItemFindAll(findForm);
        } else {
            ElMessage.error(res.message);
        }
    });
}
// 表单验证
interface RuleForm {
    id: number
    name: string
    itemName: string
    userName: string
    userNameOne: string
    userNameTwo: string
    userNameThree: string
    isDel: string
}

const ruleFormRef = ref<FormInstance>()
const userItemForm = reactive<RuleForm>({
    id: 0,
    name: '',
    itemName: '',
    userName: '',
    userNameOne: '',
    userNameTwo: '',
    userNameThree: '',
    isDel: '',
})

const rules = reactive<FormRules<RuleForm>>({
    name: [
        { required: true, message: '请添加团队名称', trigger: 'blur' },
        { max: 10, message: '不能超过10个字', trigger: 'blur' },
    ],
    userName: [
        { required: true, message: '请添加项目负责人', trigger: 'blur' },
    ],
    userNameOne: [
        { required: true, message: '请添加成员1姓名', trigger: 'blur' },
    ],
    userNameTwo: [
        { required: true, message: '请添加成员2姓名', trigger: 'blur' },
    ],
    userNameThree: [
        { required: true, message: '请添加成员3姓名', trigger: 'blur' },
    ]
})
// 时间格式化函数
const dataFormat = (data: any) => {
    return dayjs(data).format("YYYY-MM-DD HH:mm:ss");
}
</script>

<style scoped>
.box-card {
    width: 100%;
}
</style>